<template>
  <div>
    <!-- //面包学导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/nav/home' }">主页</el-breadcrumb-item>

      <el-breadcrumb-item>系统管理</el-breadcrumb-item>

      <el-breadcrumb-item :to="{ path: '/nav/system/user' }">用户管理</el-breadcrumb-item>

    </el-breadcrumb>

    <!-- 筛选 -->
    <div class="filter"> </div>
    <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form" :model="formState" @finish="onFinish">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item :name="'input'" :label="'用户名'">
            <a-input v-model:value="formState['input']"></a-input>

          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :name="'department'" :label="'部门'">
           <a-select
        v-model:value="formState['department']"
     

      >
        <a-select-option value="1">开发部</a-select-option>
        <a-select-option value="4">市场部</a-select-option>
        <a-select-option value="5">人事部</a-select-option>
        <a-select-option value="6">测试部</a-select-option>
      </a-select>

          </a-form-item>
        </a-col>
        <a-col v-show="expand" :span="12">
          <a-form-item :name="`createtime`" :label="`创建时间`">
            <a-range-picker v-model:value="formState['createtime']" value-format="YYYY-MM-DD" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: right">
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button style="margin: 0 8px" @click="restform(formRef.resetFields())" >重置</a-button>
          <a style="font-size: 12px" @click="expand = !expand">
            <template v-if="expand">
              <UpOutlined />
            </template>
            <template v-else>
              <DownOutlined />
            </template>
            收起
          </a>
        </a-col>
      </a-row>
    </a-form>
    <!-- 操作选择 -->
   <div> 
    <a-button type="primary" ghost  @click="showDrawer" >新增</a-button>
    <a-button type="primary" ghost style="margin: 0px 5px;" @click="delUser">删除</a-button>
    <a-dropdown>
    <template #overlay>
      <a-menu @click="handleMenuClick">
        <a-menu-item key="密码重置">密码重置</a-menu-item>
        <a-menu-item key="导出Excl">导出Excl</a-menu-item>
       
      </a-menu>
    </template>
    <a-button>
      更多操作
      <DownOutlined />
    </a-button>
  </a-dropdown>
  </div>
  <!-- 表格 -->
  <a-table :row-selection="rowSelection" :columns="columns" :data-source="data"  :pagination="pagination"  @change="handleTableChange" rowKey="userId" :customRow="click">
    <template #bodyCell="{ column, text ,record}">
      <template v-if="column.dataIndex === 'name'">
        <a>{{ text }}</a>
      </template>
      <template v-else-if="column.dataIndex == 'status'">
        <span slot="action " slot-scope="text,record">
          <a-tag
            :color="record.status === '1' ? 'green'  : 'red'"
          >
              {{ record.status=="1"?"有效":"锁定" }}
          </a-tag>
        </span>
      </template>
      <template v-else-if="column.dataIndex == 'change'">
          <img src="../../assets/imgs/设置.png" alt="" style="width:15px" @click="changeUser(record)">  
          <img src="../../assets/imgs/眼睛.png" alt="" style="margin-left: 5px;width: 20px;" @click="eyesee(record)">
        <setting-outlined />
        <eye-outlined />
       
      </template>

    </template>
  </a-table>
  <!-- 抽屉 -->
  <a-drawer
    v-model:visible="visible"
    class="custom-class"
    style="color: red"
    :title='switchs==false ? "新增用户":"编辑用户"' 
    placement="right"
    @after-visible-change="afterVisibleChange"
  >
  <!-- 抽屉表单 -->

  <a-form
    :model="DrawerformState"
    name="basic"
    :label-col="{ span: 8 }"
    :wrapper-col="{ span: 16 }"
    autocomplete="off"
    @finish="DraweronFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item
      label="用户名"
      name="username"
      :rules="[{ required: true, message: '请输入用户名!' }]"
    >
      <a-input v-model:value="DrawerformState.username" />
    </a-form-item>

    <a-form-item
      label="密码"
      name="password"
     
    >
      <a-input-password v-model:value="DrawerformState.password" />
    </a-form-item>

    <a-form-item
      label="邮箱"
      name="email"
     
    >
      <a-input v-model:value="DrawerformState.email" />
    </a-form-item>
    <a-form-item
      label="手机"
      name="mobile"
     
    >
      <a-input v-model:value="DrawerformState.mobile" />
    </a-form-item>
    <a-form-item
      label="角色"
      name="roleId"
      :rules="[{ required: true, message: '请输入角色!' }]"
    >
    <a-tree-select
    v-model:value="DrawerformState.roleId"
    style="width: 100%"
    :tree-data="treeData2"
    tree-checkable
    allow-clear
    :show-checked-strategy="SHOW_PARENT"
    placeholder="Please select"
  />


    </a-form-item>
    <a-form-item
      label="部门"
      name="deptId"
    >
    <a-tree-select
    v-model:value="DrawerformState.deptId"
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="Please select"
    allow-clear
    tree-default-expand-all
    :tree-data="treeData"
  >
    <template #title="{ value: val, title }">
      <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
      <template v-else>{{ title }}</template>
    </template>
  </a-tree-select>
    </a-form-item>
    <a-form-item
      label="状态"
      name="status"
      :rules="[{ required: true, message: '请选择状态' }]"
    >
    <a-radio-group v-model:value="DrawerformState.status">
      <a-radio :value="'1'">锁定</a-radio>
      <a-radio :value="'2'">有效</a-radio>
      
    </a-radio-group>
    </a-form-item>
    <a-form-item
      label="性别"
      name="ssex"
      :rules="[{ required: true, message: '请选择性别' }]"
    >
    <a-radio-group v-model:value="DrawerformState.ssex">
      <a-radio :value="'1'">男</a-radio>
      <a-radio :value="'0'">女</a-radio>
      <a-radio :value="'2'">保密</a-radio>
      
    </a-radio-group>
    </a-form-item>


   

    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button type="primary" >取消</a-button>
      <a-button type="primary" html-type="submit" style="margin-left: 10px;">提交</a-button>
    </a-form-item>
  </a-form>
  </a-drawer>

  <!-- 眼睛对话框 -->
  <div>
  
    <a-modal v-model:visible="eyestxt" title="用户信息" @ok="okclose" width="700px">
        <div style="display: flex; align-items: center;">
            <div><img :src="`http://xawn.f3322.net:8002/distremote/static/avatar/${eyedata.avatar}`" alt="" style="width: 100px;height: 100px;"></div>
          <div style="margin-left: 15px;">
            <table id="userinfo" style="width: 400px;margin-left: 20px;">
                <tr><td>账户:{{eyedata.username}}</td> <td >部门:{{eyedata.deptName  }}</td></tr>
                <tr><td>角色:{{ eyedata.roleName }}</td> <td >状态:{{ eyedata.roleName==1?"有效":"锁定" }}</td></tr>
                <tr><td>性别:{{ eyedata.ssex==1?"男":eyedata.ssex==0?"女":"保密" }}</td> <td >创建时间:{{eyedata.createTime}}</td></tr>
                <tr><td>电话:{{ eyedata.mobile }}</td> <td >最近登录:{{ eyedata.lastLoginTime }}</td></tr>
                <tr><td>邮箱:{{ eyedata.email }}</td> <td >描述:{{ eyedata.descriotion }}</td></tr>


            </table>


          </div>


        </div>


    </a-modal>
  </div>


  </div>

</template>

<script  setup>
import { ElMessage } from "element-plus";
import { reactive, ref ,computed, defineComponent,onMounted,createVNode} from 'vue';
import { DownOutlined, UpOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import {userApi,createUserApi,deluserApi,changeuserApi} from "../../apis/user";
import { Modal } from 'ant-design-vue';
const DrawerformState = ref({
      username: '',
      password: '1234qwer',
      roleId:"",
      status:"",
      ssex:"",
      email:"",
      mobile:"",
      deptId:"",
      userId:""

    });
const serachDate=ref({
  username:"",
  deptId:'',
  createTimeFrom:'',
  createTimeTo:""
})
const pagination = ref ({
      total: 200,
      current: 1,
      pageSize: 10
    });
const expand = ref(false);
const formRef = ref();
const formState = reactive({
});
onMounted(()=>{
  getAllUser()
})

//开关值判断是新增用户还是编辑用户
const switchs=ref(false);
 //编辑用户
  function changeUser(column){
    console.log('123',column);
    switchs.value=true
    DrawerformState.value.username= column.username
    DrawerformState.value.roleId= column.roleId 
    DrawerformState.value.status= column.status 
    DrawerformState.value.ssex= column.ssex 
    DrawerformState.value.email= column.email 
    DrawerformState.value.mobile= column.mobile 
    DrawerformState.value.deptId= column.deptId 
    DrawerformState.value.userId= column.userId 
      
  console.log('DrawerformState.value.userId', DrawerformState.value.userId)


  

    showDrawer()
    //回显数据
     

  }

  


//表格
const columns= ref([
  {
    title: '用户名  ',
    
    dataIndex: 'username',
    sorter: {
      compare: (a, b) => a.username.length - b.username.length,
      multiple: 1,
    },
  },
  {
    title: '性别',
    dataIndex: 'ssex',
    key:"ssex",
    customRender:function({text}){
      
      if(text=='0'){
        return "女";
      }else if(text=='1'){
        return "男"
      }
      else{
        return "保密"
      }
      
    },
    filters: [
      { text: '男', value: '1' },
      { text: '女', value: '0' },
    ],
  },
  {
    title: '邮箱',
    key:'1',
    dataIndex: 'email',
  },
  {
    title: '部门',
    key:'2',
    dataIndex: 'deptName',
  },
  {
    title: '电话',
    key:'3',
    dataIndex: 'mobile',
  },
  {
    title: '状态',
    key:"status",
    dataIndex: 'status',
    
    
  },
  {
    title: '创建时间',
    key:"5",
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    
    dataIndex: 'change',
  },
]);
const data = ref([
  // {
  //   key: '1',
  //   username: 'John Brown',
  //   age: 32,
  //   address: 'New York No. 1 Lake Park',
  // },
  // {
  //   key: '2',
  //   username: 'Jim Green',
  //   age: 42,
  //   address: 'London No. 1 Lake Park',
  // },
  // {
  //   key: '3',
  //   username: 'Joe Black',
  //   age: 32,
  //   address: 'Sidney No. 1 Lake Park',
  // },
  // {
  //   key: '4',
  //   name: 'Disabled User',
  //   age: 99,
  //   address: 'Sidney No. 1 Lake Park',
  // },
]);
 //拿到所有的用户
 async  function getAllUser(){
     const res=await userApi({pageSize:pagination.value.pageSize,pageNum:pagination.value.current})
    console.log("用户数据",res);
    data.value=res.rows
    
    pagination.value.total=res.total
      

      console.log("data.vale",data.value); 
  }


//表单值
const onFinish =async values => {
  console.log('Received values of form: ', values);

  if(values.createtime){
    serachDate.value.createTimeFrom=values.createtime[0]
    serachDate.value.createTimeTo=values.createtime[1]
  }
  
  serachDate.value.username=values.input
  serachDate.value.deptId=values.department
 


 let res= await userApi(serachDate.value)
 console.log("搜索数据",res);

 data.value=res.rows
    
    pagination.value.total=res.total
      


};
  // 重置表单
  async function restform(){
    // formRef.resetFields()
 
    const res=await userApi({})
  data.value=res.rows
    
    pagination.value.total=res.total
  
 
}



  // /计算属性

 

//选择是否导出
const handleMenuClick = e => {
      console.log('click', e);
    };

  //表格

  //定义一个删除列表

  //定义删除id
  const  deluserId=ref([])
  const dellist=ref([])
  const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows[0]);
        dellist.value=selectedRows
        dellist.value=dellist.value.map(m=>m.username)
        deluserId.value=selectedRows.map(m=>m.userId)

        console.log("删除id",deluserId.value)
       console.log('dellist.value',dellist.value);

      },
      getCheckboxProps: (record) => ({
        // disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
    //删除用户
    function delUser(){
      console.log(123);
        const notie=dellist.value.join()
      Modal.confirm({
        title: '确定删除用户?',
        icon: createVNode(ExclamationCircleOutlined),
        content: notie,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log('OK',deluserId.values);

          deluserApi(deluserId.value)
          .then((res)=>{
              console.log("删除了吗",res);
              getAllUser()
              ElMessage.success("删除成功")
          })

        },
        onCancel() {
          console.log('Cancel');
        },
      });
    



    }

    //分页
      
      
   
    const handleTableChange = (current, pageSize,filters
    ) => {
        console.log('current',current);
        console.log('999',pagination.value.current);
        pagination.value.current=current.current
        pagination.value.pageSize=current.pageSize
        console.log('filters',filters);
        getAllUser()
    };


    //抽屉
    const visible = ref(false);

const afterVisibleChange = (bool) => {
  console.log('visible', bool);
  if(bool==false){
    switchs.value=false

    //重置数据
    DrawerformState.value.username=""
    DrawerformState.value.roleId= "" 
    DrawerformState.value.status= "" 
    DrawerformState.value.ssex= ""
    DrawerformState.value.email= "" 
    DrawerformState.value.mobile= "" 
    DrawerformState.value.deptId= "" 
    DrawerformState.value.userId= "" 
  }
  
};

const showDrawer = () => {
  
  visible.value = true;
};
  //  抽屉表单
  
    const DraweronFinish = async(values) => {
   



      console.log('Success:', values);
      //新增用户
        if(switchs.value==false){






          let res= await createUserApi(values)
      console.log("新增用户",res);
          ElMessage.success('新增成功')
        }else{

            //处理筛选出提交数据不为null的
              DrawerformState.value.keys
              console.log('DrawerformState.value',Object.entries(DrawerformState.value))
             let newarry= Object.entries(DrawerformState.value).filter(m=>{
                 return m[1] !=null||undefined
              })
              const arr=  Object.fromEntries(newarry)
              console.log("newarry",arr)
              



            let res=await changeuserApi(arr)
            console.log("修改用户",res);
      ElMessage.success('修改成功')
                //重置数据
                DrawerformState.value.username= ""
    


        }


     
      getAllUser()
    };
    
    




    const onFinishFailed = (errorInfo) => {
      console.log('Failed:', errorInfo);
    };

    //部门树形选择
    const treeData = ref([
      {
        title: '开发部',
        value: '1',
        children: [
          {
            title: '开发一部',
            value: '2',
            
          },
          {
            title: '开发二部',
            value: '3',
          },
        ],
      },

      {
        title: '市场部',
        value: '4',
       
      },
      {
        title: '人事部',
        value: '5',
       
      },
      {
        title: '测试部',
        value: '6',
       
      },
    ]);
    const treeData2= ref([
      {
        title: '管理员',
        value: '1',
      },
      {
        title: '注册用户',
        value: '2',
       
      },
      {
        title: '普通用户',
        value: '3',
       
      },
      {
        title: '商户',
        value: '4',
       
      },
      {
        title: 'chole',
        value: '5',
       
      },
    ]);

      //眼睛对话框
      const eyedata = ref({
      username: '',
      descriotion: '',
      createTime:"",
      status:"",
      ssex:"",
      email:"",
      mobile:"",
      deptName:"",
      lastLoginTime:"",
      roleName:"",
      avatar:""
    });
    

      const eyestxt = ref(false);

const eyesee = (column) => {
  eyestxt.value = true;
  console.log("行数据",column);
  eyedata.value.username= column.username
    eyedata.value.descriotion= column.descriotion 
    eyedata.value.status= column.status 
    eyedata.value.ssex= column.ssex 
    eyedata.value.email= column.email 
    eyedata.value.mobile= column.mobile 
    eyedata.value.deptName= column.deptName 
    eyedata.value.lastLoginTime= column.lastLoginTime 
    eyedata.value.createTime= column.createTime 
    eyedata.value.roleName= column.roleName 
    eyedata.value.avatar= column.avatar 





};

const okclose = () => {
  console.log(e);
  eyestxt.value = false;
};

</script>
    
<style lang="scss">
.filter {
  margin-top: 20px;
}

#components-form-demo-advanced-search .ant-form {
  max-width: none;
}

#components-form-demo-advanced-search .search-result-list {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 2px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}

[data-theme='dark'] .ant-advanced-search-form {
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid #434343;
  padding: 24px;
  border-radius: 2px;
}

[data-theme='dark'] #components-form-demo-advanced-search .search-result-list {
  border: 1px dashed #434343;
  background: rgba(255, 255, 255, 0.04);
}



</style>